﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Algorithms
{
    /// <summary>
    /// 反转一个整数
    /// https://leetcode.com/problems/reverse-integer/
    /// </summary>
    public class ReverseInteger
    {
        /// <summary>
        /// 反转字符串
        /// </summary>
        /// <param name="x"></param>
        /// <returns></returns>
        public static int Action1(int x)
        {
            var flag = x > 0;
            x = flag ? x : -1 * x;
            var numStr = x.ToString();
          
            var len = numStr.Length;

            var chars = new char[len];

            for (var i = 0; i <(len); i++)
            {
                chars[i] = numStr[len - i-1];
            }

            var tStr = new string( chars);

            if (int.TryParse(tStr, out int result))
            {
                return flag ? result : result * -1;
            }

            return 0;
        }
        /// <summary>
        /// 使用数学方式按位移动
        /// </summary>
        /// <param name="x"></param>
        /// <returns></returns>
        public static int Action2(int x)
        {
            long r = 0;
            while (x != 0)
            {
                r = r * 10 + x % 10;
                x = x / 10;
            }

            return (r > int.MaxValue || r < int.MinValue )? 0 : (int)r;
        }

        public static int Action3(int x)
        {
            long r = 0;

            for (; x != 0; r = (r * 10 + x % 10), x /= 10) ;

            return (r > int.MaxValue || r < int.MinValue) ? 0 : (int)r;
        }

    }
}
